import { Component } from 'react'
import { View, Block,ScrollView,Text,Swiper,SwiperItem,Image} from '@tarojs/components'
import {NavBar,SubmitBar,Icon,Skeleton,ActionSheet,Empty  } from '@antmjs/vantui'
import { connect } from 'react-redux'
import { LoadVarietyActionAsync} from '../../redux/action/VarietyAction';
import { ClearShoppingAction} from '../../redux/action/shoppingAction';
import { ChangeLoadingAction } from '../../redux/action/loadingAction';
import './index.less'
import Taro from '@tarojs/taro';
import List from './components/list';
import http from '../../service/http';
import dev from '../../../config/dev';

const isH5 = process.env.TARO_ENV === 'h5'

@connect(	state => ({
    varietyList:state.varietyList,
    shoppingCart:state.shoppingCart
	}),
	{LoadVarietyActionAsync,ClearShoppingAction}
)
class Verticalnav extends Component {
  state={
    TabCur: 0,
    MainCur: 0,
    VerticalNavTop: 0,
    // list: [],
    load: true,
    // listCur: null,
    num:null,
    tableName:'',
    tableNumId:0,
    loading:true,
    isShowModal:false
  }

  // UNSAFE_componentWillMount () { console.log('UNSAFE_componentWillMount,组件还没挂载前');if(isH5){console.log('你当前环境为H5')} }

  componentDidMount () {
    this.props.ClearShoppingAction()
    let that = this
    this.props.LoadVarietyActionAsync().then(()=>{
      that.setState({loading:false})
    })
    // let list = [{}];
    // for (let i = 0; i < 5; i++) {
    //   list[i] = {};
    //   list[i].name = '素菜类'+i;
    //   list[i].id = i;
    // }
    // this.setState({
    //   list: list,
    //   // listCur: list[0]
    // })
  }

  // shouldComponentUpdate (nextProps,nextState) { console.log('shouldComponentUpdate,组件是否需要更新',nextProps,nextState);return true }

  // componentWillUnmount () { console.log('componentWillUnmount,组件卸载前') }

  // componentDidShow () { console.log('componentDidShow,组件显示后') }

  // componentDidHide () { console.log('componentDidHide,组件隐藏后') }


      // onLoad
  async onLoad (options) {
    // scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    this.setState({num:options.num,tableName:options.tableName,tableNumId:options.tableNumId})
  }

  // onReady
  onReady () {}

  // 对应 onShow
  componentDidShow () {}

  // 对应 onHide
  componentDidHide () {}

  // 对应 onPullDownRefresh，除了 componentDidShow/componentDidHide 之外，
  // 所有页面生命周期函数名都与小程序相对应
  onPullDownRefresh () {}

  tabSelect(id) {
    this.setState({
      TabCur: id,
      MainCur: id,
      VerticalNavTop: (id - 1) * 50
    })
  }
  VerticalMain(e) {
    let that = this;
    let list = this.props.varietyList;
    let tabHeight = 0;
    if (this.state.load) {
      for (let i = 0; i < list.length; i++) {
        let view = Taro.createSelectorQuery().select("#main-" + list[i].id);
        view.fields({
          size: true
        }, data => {
          list[i].top = tabHeight;
          if(data){tabHeight = tabHeight + data.height}
          list[i].bottom = tabHeight;     
        }).exec();
      }
      that.setState({
        load: false,
        list: list
      })
    }
    let scrollTop = e.detail.scrollTop + 20;
    for (let i = 0; i < list.length; i++) {
      if (scrollTop > list[i].top && scrollTop < list[i].bottom) {
        that.setState({
          VerticalNavTop: (list[i].id - 1) * 50,
          TabCur: list[i].id
        })
        return false
      }
    }
  }
  render () {
    return (
      <Block>
        <NavBar 
          title={'江西南客餐饮店'+this.state.tableName+'('+this.state.num+'人)'}
          // leftText='返回'
          leftArrow
          className='nav-style'
          onClickLeft={() => (Taro.navigateBack())}
        />
        <Swiper
          className='test-h'
          indicatorColor='#959595'
          indicatorActiveColor='#eff0f1'
          vertical={false}
          circular={false}
          indicatorDots
          autoplay
        >
          <SwiperItem>
            <Image src={dev.baseUrl+'/files/ban1.jpeg'} style={{width:'100%',height:"100%"}}></Image>
          </SwiperItem>
          <SwiperItem>
            <Image src={dev.baseUrl+'/files/ban2.jpeg'} style={{width:'100%',height:"100%"}}></Image>
          </SwiperItem>
          <SwiperItem>
            <Image src={dev.baseUrl+'/files/ban3.jpeg'} style={{width:'100%',height:"100%"}}></Image>
          </SwiperItem>
        </Swiper>
        <Skeleton row='18' loading={this.state.loading}>
        <View className='VerticalBox'>
          <ScrollView className='VerticalNav nav VerticalNav-height' scrollY scrollWithAnimation scrollTop={this.state.VerticalNavTop} > 
            {
              this.props.varietyList.map((item,index)=>{
                return <View
                  className={index==this.state.TabCur?'cu-item cur':'cu-item'} 
                  key={item.key}
                  onClick={this.tabSelect.bind(this,index)}
                  style={{position:'relative'}}
                >
                  {item.className}
                  {this.props.shoppingCart.typeNum.length===0||this.props.shoppingCart.typeNum[item.key].number===0?null:
                  <View style={{fontSize:'20rpx',position:'absolute',right:'0',top:'0',backgroundColor:'red',color:'#fff',borderRadius:'50%',textAlign:'center',height:'30rpx',width:'30rpx',lineHeight:'30rpx'}}>{this.props.shoppingCart.typeNum[item.key].number}</View>
                  }
                </View>
              })
            }
          </ScrollView>
          <ScrollView className='VerticalMain VerticalNav-height' scrollY scrollWithAnimation scrollIntoView={"main-"+this.state.MainCur} onScroll={this.VerticalMain.bind(this)}>
            {
              this.props.varietyList.map((item,index)=>{
                return <View
                  className='padding-top padding-lr' 
                  key={item.key}
                  id={"main-"+index}
                >
                  <View className='variety-type'>
                      {item.className} 
                  </View>
                  {
                    item.listChild.map((item2)=>{
                      return <List key={item2.id} obj={item2}></List>
                    })
                  }
                </View>
              })
            }
          </ScrollView>
        </View>
        </Skeleton>
        <SubmitBar
          price={this.props.shoppingCart.money*100}
          buttonText='选好了'
          onSubmit={() => {
            let that=this
            if(!this.state.isShowModal){
              this.setState({isShowModal:true})
              return
            }else{
              if(this.props.shoppingCart.num===0){Taro.showToast({title:'请选择菜品',icon:'none'})}
              else{
                Taro.requestSubscribeMessage({
                  tmplIds:['lxQ2Z5RxGg5F5pmSEFxNd1isk0hzYdCsopeYX1T3ung','uUAljnS5sanQ-qyiiurK0hSwPhIsL8dv8xytTnKEWJo'],
                  success:(res)=>{
                    console.log(res)
                    Taro.navigateTo({
                      url:'/pages/order/index?num='+that.state.num+'&tableNumId='+this.state.tableNumId
                    })
                  }
                })
              }
            }
          }}
          buttonType='info'
          decimalLength={2}
          safeAreaInsetBottom={false}
        >
          <Icon name='shopping-cart' size='32px' info={this.props.shoppingCart.num} color='#01b6fd' onClick={()=>{
            this.setState({isShowModal:true})
          }}
          />
          <Text className='shopping-right-text' onClick={()=>{
            this.setState({isShowModal:true})
          }}
          >已经点{this.props.shoppingCart.num}份菜品</Text>
        </SubmitBar>
        <View>
        <ActionSheet
          show={this.state.isShowModal}
          onClose={() => this.setState({isShowModal:false})}
          safeAreaInsetBottom={false}
          zIndex={2}
          style={{minHeight:'20vh',overflowY:'auto',padding:'0 20rpx 100rpx 20rpx'}}
        >
          <View
            onClick={()=>{
              let that=this
              Taro.showModal({
                title: '提示',
                content: '你确定要清空购物车吗？',
                success: function (res) {
                  if (res.confirm) {
                    that.props.ClearShoppingAction()
                  } else if (res.cancel) {
                    // console.log('用户点击取消')
                  }
                }
              })
            }}
            style={{fontSize:'27rpx',color:'#c1c1c1',textAlign: 'right',padding: '20rpx 0',borderBottom: '1rpx #f1f1f1 solid'}}
          ><Icon name='delete-o' size='30rpx'></Icon>清空已点</View>
          {
            this.props.shoppingCart.data.map((item2)=>{
              return item2.num>0?<List key={item2.id} obj={item2} not></List>:null
            })
          }
          {
            this.props.shoppingCart.num===0?<View
              class='customImage'
            ><View style={{color:'#c1c1c1'}}>空空如也</View></View>:null
          }
        </ActionSheet>
        </View>
      </Block>
    );
  }
}
Verticalnav.defaultProps = {}
export default Verticalnav

